package cmd

import (
	"app/cmd/excel"
	"app/cmd/orm"
	"app/cmd/pack"
	"app/controllers"
	"app/cron"
	"app/daos"
	"app/env"
	"bufio"
	"fmt"
	"github.com/fwhezfwhez/errorx"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"net/http"
	"os"
	"path/filepath"
)

func serverFunc(args []string) {
	cron.InitCronJobs() //初始化计时器任务
	router := env.GetGin()
	router.POST("/:controller/:action", func(c *gin.Context) {
		response := controllers.Run(c)
		c.JSON(http.StatusOK, response)
	})

	server := &http.Server{
		Addr:    env.Cfg.Port,
		Handler: router,
	}

	//go watcher.WatchConfigChange()
	//go watcher.WatchEtcdChange()

	//go grpc.CreateService()
	logrus.Info("http server start on port", env.Cfg.Port)
	if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
		logrus.Fatal(err)
	}

	//quit := make(chan os.Signal)
	//signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	//<-quit
}

func excelFunc(args []string, excelDir string, jsonDir string, goDir string) {
	excelDir = filepath.FromSlash(excelDir)
	jsonDir = filepath.FromSlash(jsonDir)
	goDir = filepath.FromSlash(goDir)

	if _, err := os.Stat(goDir); os.IsNotExist(err) {
		// 目录不存在，创建目录
		err := os.Mkdir(goDir, 0755)
		if err != nil {
			fmt.Println("创建目录失败:", err)
			return
		}
	}

	if _, err := os.Stat(jsonDir); os.IsNotExist(err) {
		// 目录不存在，创建目录
		err := os.Mkdir(jsonDir, 0755)
		if err != nil {
			fmt.Println("创建目录失败:", err)
			return
		}
	}

	var isPack bool
	if len(args) == 0 {
		isPack = false
	} else {
		isPack = args[0] == "pack"
	}

	excel.ExportExcel(isPack, excelDir, jsonDir, goDir)
}

func packFunc(args []string, resourcesDir string, jsonDir string, staticDir string) {
	//jsonDir = filepath.FromSlash(jsonDir)
	//staticDir = filepath.FromSlash(staticDir)

	if _, err := os.Stat(resourcesDir); os.IsNotExist(err) {
		// 目录不存在，创建目录
		err := os.Mkdir(resourcesDir, 0755)
		if err != nil {
			fmt.Println("创建目录失败:", err)
			return
		}
	}

	pack.FuncPack(resourcesDir, jsonDir, staticDir)
}

func ormFunc(args []string) {
	var outDir = "./model/"
	fmt.Println("start processing orm file--->")
	if _, err := os.Stat(outDir); os.IsNotExist(err) {
		_ = os.Mkdir(outDir, 0777)
	}

	for _, table := range daos.OrmS {
		fmt.Println("start processing table: ", table.TableName(), "...")
		orm.ProcessTable(table, outDir)
	}

	fmt.Println("end processing orm file--->")
}

func WriteFile(args []string, dataStr string) {
	baseDir := env.BaseDir
	filePath := baseDir + "/e.txt"
	data := []byte(dataStr)
	file, err := os.OpenFile(filePath, os.O_CREATE|os.O_RDWR, 0666)
	defer file.Close()
	if err != nil {
		fmt.Println(errorx.Wrap(err))
	}

	writer := bufio.NewWriter(file)
	_, err = writer.Write(data)
	if err != nil {
		fmt.Println(errorx.Wrap(err))
	}

	writer.Flush()
}

func test() {

}
